package com.wenzi.rule.verification.form;

import java.lang.reflect.Field;
import java.util.*;

public class FormUtil {

    public static List<Form> parseForm(Object form,String path){
        int index = path.indexOf(".");
        if (index < 0){
            return Arrays.asList(new Form(form));
        }

        String parentName = path.substring(0, index);
        String childPath = path.substring(index + 1);
        Object child = fetchChild(form, childPath);

        if (child instanceof Collection){
            List<Form> list = new ArrayList<>();
            ((Collection)child).forEach(t->{
                list.addAll(parseForm(form,parentName,t,childPath));
            });
            return list;
        }else{
            return parseForm(form,parentName,child,childPath);
        }
    }



    private static List<Form> parseForm(Object parentForm, String parentName, Object childForm, String childPath){
        if (childForm == null){
            return Collections.EMPTY_LIST;
        }

        List<Form> list = parseForm(childForm, childPath);
        if (parentName.endsWith("List")){
            parentName.substring(0,parentName.length() - 4);
        }
        String name = parentName;

        list.forEach(t->{
            t.setObjects(name,parentForm);
        });
        return list;
    }

    private static Object fetchChild(Object form, String path){
        int index = path.indexOf(".");
        String name = path;
        if (index > -1){
            name = path.substring(0, index);
        }

        try {
            Field field = form.getClass().getDeclaredField(name);
            field.setAccessible(true);
            return field.get(form);
        }catch (Exception e){

        }
        return null;
    }
}
